package com.anxuan.wiki.service;


import com.anxuan.wiki.domain.Ebook;
import com.anxuan.wiki.domain.EbookExample;
import com.anxuan.wiki.mapper.EbookMapper;
import com.anxuan.wiki.req.EbookQueryReq;
import com.anxuan.wiki.req.EbookSaveReq;
import com.anxuan.wiki.resp.EbookQueryResp;
import com.anxuan.wiki.resp.PageResp;
import com.anxuan.wiki.util.CopyUtil;
import com.anxuan.wiki.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class EbookService {
    @Resource
    private EbookMapper ebookMapper;
    @Resource
    private SnowFlake snowFlake;


    //显示电子书   查询电子书
    public PageResp<EbookQueryResp> list(EbookQueryReq req) {
        PageHelper.startPage(req.getPage(), req.getSize());
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%" + req.getName() + "%");
        }
        if (!ObjectUtils.isEmpty(req.getCategoryId2())) {
            criteria.andCategory2IdEqualTo(req.getCategoryId2());
        }
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);
        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);


        /*
        持久层返回List<Ebook>
        需要转换成 List<EbookResp>
        再返回controller
         */
        List<EbookQueryResp> respList = new ArrayList<>();
       /* for (Ebook ebook:ebookList) {
         对象复制   EbookResp ebookResp = CopyUtil.copy(ebook, EbookResp.class);
            respList.add(ebookResp);

        }*/

        List<EbookQueryResp> list = CopyUtil.copyList(ebookList, EbookQueryResp.class);
        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;


    }

    //保存
    public void save(EbookSaveReq req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            //新增
            ebook.setId(snowFlake.nextId());
            ebook.setViewCount(0);
            ebook.setDocCount(0);
            ebook.setVoteCount(0);
            ebookMapper.insert(ebook);
        } else {
            //更新
            ebookMapper.updateByPrimaryKey(ebook);
        }


    }


    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }

}
